<?php

namespace app\admin\controller;

use app\admin\model\ActivityOrder;
use app\admin\model\UserCountry;
use app\admin\model\UserDegree;
use app\admin\model\UserMajor;
use Think\Controller;
use think\Db;
use app\admin\model\Balance;
use app\admin\model\Magazine;
use app\admin\model\MagazineArticle;
use app\admin\model\Course;
use app\admin\model\MagazineYear;
use app\admin\model\User;
use app\admin\model\TalkShow;

class Experience extends Basic
{

    /**
     * 初始化父类
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 渠道统计导出
     */
    public function channel_total_export()
    {
        $keys = input('keys');

        $map = array(
            'status' => array('neq', 0)
        );
        if ($keys) {
            $map['title'] = array('like', '%' . $keys . '%');
        }
        //实例化数据库
        $channel = new \app\admin\model\Channel();
        $user = new \app\admin\model\User();

        $list = $channel->where($map)->order('id desc')->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $v['drainage_count'] = $user->where(array('source_type' => 3, 'source_id' => $v['id']))->count(1);
                $v['bind_mobile_count'] = $user->where(array('source_type' => 3, 'source_id' => $v['id'], 'is_bind_mobile' => 1))->count(1);
                $new_info[] = array(
                    'title' => $v['title'],
                    'describe' => $v['describe'],
                    'drainage_count' => $v['drainage_count'],
                    'bind_mobile_count' => $v['bind_mobile_count'],
                );
            }
            $name = 'channel_count';
            $header = array(
                '渠道名称', '渠道描述', '引流人数', '引流人数', '绑定手机人数');
            excelExport($name, $header, $new_info);
        } else {
            echo '暂无内容';
        }
    }

    /**
     * 渠道统计明细导出
     */
    public function channel_detailed_export()
    {
        $channel_id = input('channel_id');
        $keys = input('keys');
        $start_time = input('start_time');
        $end_time = input('end_time');
        if (!$channel_id) {
            json_fail('获取渠道id错误');
        }

        //实例化数据库
        $user = new \app\admin\model\User();

        $map = array(
            'source_type' => 3,
            'source_id' => $channel_id
        );
        if ($keys) {
            $map['nickname_old|mobile'] = array('like', '%' . $keys . '%');
        }
        if ($start_time && $end_time) {
            $map['timestamp'] = array('between', array(strtotime($start_time), strtotime($end_time)));
        }

        $userList = $user->where($map)->field('nickname,avatar_url,real_name,old_nickname,mobile,is_bind_mobile,timestamp')->select();

        if (!$userList) {
            json_fail('暂无数据');
        }

        if ($userList) {
            foreach ($userList as $k => $v) {
                $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '--';
                $v['timestamp'] = $v['timestamp'] ? date('Y-m-d H:i:s', $v['timestamp']) : '--';
                $new_info[] = array(
                    'nickname' => $v['nickname'],
                    'real_name' => $v['real_name'],
                    'mobile' => $v['mobile'],
                    'timestamp' => $v['timestamp'],
                );
            }
            $name = 'channel_detail';
            $header = array(
                '昵称', '姓名', '手机号码', '注册时间');
            excelExport($name, $header, $new_info);
        } else {
            echo '暂无内容';
        }
    }

    /**
     * 导出分销管理列表
     */

    public function balance_list_export()
    {
        $key = input('key', '');
        $map['old_nickname|nickname'] = ['like', '%' . $key . '%'];

        $user = new \app\admin\model\User();

        $list = $user->field('id,old_nickname,nickname,avatar_url,total_profit_price,total_receive_price,drainage_count')
            ->where($map)->order('id desc')->select();

        if (empty($list)) {
            json_fail('暂无数据');
        }
        foreach ($list as $k => $v) {
            $v['can_withdraw'] = ($v['total_profit_price'] - $v['total_receive_price']) / 100 ? ($v['total_profit_price'] - $v['total_receive_price']) / 100 : '--';
            $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '--';
            $v['total_profit_price'] = $v['total_profit_price'] ? $v['total_profit_price'] / 100 : '--';
            $v['total_receive_price'] = $v['total_receive_price'] ? $v['total_receive_price'] / 100 : '--';
//            $v['avatar_url'] = $v['avatar_url'] ? json_decode($v['avatar_url']) : '';
            $v['avatar_url'] = $v['avatar_url'] ? $v['avatar_url'] : '';


            $new_info[] = array(
                'nickname' => $v['nickname'],
                'avatar_url' => $v['avatar_url'],
                'total_profit_price' => $v['total_profit_price'],  //收益
                'total_receive_price' => $v['total_receive_price'],//已提现
                'can_withdraw' => $v['can_withdraw'], //可提现金额
                'drainage_count' => $v['drainage_count'],
            );

        }

        $name = 'balance_list_export';
        $header = array('微信昵称', '微信头像', '收益总金额', '已提现金额', '可提现金额', '拉新用户人数');

        excelExport($name, $header, $new_info);
    }

    /**
     * 导出提现记录列表 文件
     */

    public function balance_recode_export()
    {
        $id = input('id', '');
        if (empty($id)) {
            json_fail('缺少ID参数');
        }
        $key = input('key', '');
        $start_time = input('start_time', '');
        $end_time = input('end_time', '');

        $obj = new Balance();

        if (!empty($key)) {
            $one['a.nickname|a.old_nickname'] = ['like', '%' . $key . '%'];
        } else {
            $one = '';
        }

        if (!empty($start_time) && !empty($end_time)) {
            $start_t = strtotime($start_time);
            $end_t = strtotime($end_time);

            $time = array($start_t, $end_t);  //时间

            $two['b.time'] = ['between', $time];
        } else {
            $two = '';
        }

        $res = $obj->alias('b')
            ->field('a.nickname,a.old_nickname,a.avatar_url,b.user_id,b.type,b.price,b.current_price,b.time,b.is_arrival,b.arrival_reason')
            ->where('user_id', $id)
            ->where('b.type', 'eq', 2)
            ->join('user a', 'a.id=b.user_id', 'left')
            ->where($one)
            ->where($two)
            ->select();
        if (empty($res)){
            json_fail('暂无数据');
        }
        foreach ($res as $k => $v) {

            $v['price'] = $v['price'] ? $v['price'] / 100 : '--';  //提现金额
            $v['current_price'] = $v['current_price'] ? $v['current_price'] / 100 : '--'; //提现后金额
            $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '--';
//            $v['avatar_url'] = $v['avatar_url'] ? json_decode($v['avatar_url']) : '';
            $v['avatar_url'] = $v['avatar_url'] ? $v['avatar_url'] : '';
            $v['time'] = $v['time'] ? date('Y-m-d H:i:s', $v['time']) : '--';
            $v['is_arrival'] = $v['is_arrival'] == 1 ? '提现成功' : $v['is_arrival'] == 2 ? '提现未到帐' : '待提现';

            $new_info[] = array(
                'nickname' => $v['nickname'],
                'avatar_url' => $v['avatar_url'],
                'price' => $v['price'],
                'current_price' => $v['current_price'],
                'time' => $v['time'],
                'is_arrival' => $v['is_arrival'],
                'arrival_reason' => $v['arrival_reason'],

            );


        }
        $name = 'balance_recode_export';
        $header = array('微信昵称', '微信头像', '提现金额', '提现后剩余金额', '提现时间', '提现状态', '备注');

        excelExport($name, $header, $new_info);


    }

    /**
     * 导出订单 文件
     */
    public function order_export()
    {
        $start_time = input('start_time', ''); //开始日期
        $end_time = input('end_time', ''); //结束日期
        $type = input('type', '');    //订单类型
        $order_sn = input('sn', '');   //订单号或内容标题
        $nickname = input('nickname', '');   //用户名称

        if (!empty($type)) {
            $one['o.type'] = ['eq', $type]; //类型
        } else {
            $one = '';
        }
        if (!empty($order_sn)) {
            $two['sn|title'] = ['eq', $order_sn]; //订单号或内容标题
        } else {
            $two = '';
        }

        if (!empty($nickname)) {
            $shree['u.nickname|u.old_nickname'] = ['eq', $nickname];
        } else {
            $shree = '';
        }

        if (!empty($start_time) && !empty($end_time)) {

            $start_t = strtotime($start_time);
            $end_t = strtotime($end_time);
//                    dump($start_t);
//                    dump($end_t);
            $time = array($start_t, $end_t);  //时间
            $four['o.create_time'] = ['between', $time];
        } else {
            $four = '';
        }

        $dataList['list'] = \app\admin\model\Order::alias('o')
            ->field('o.id ,o.pid,o.sn,o.picture,o.title,o.type,o.buy_type,o.price,o.pay_price,o.create_time,o.pay_time,u.nickname,u.old_nickname,u.avatar_url')
            ->join('user u', 'u.id=o.user_id')
            ->where('o.status',1)
            ->where($one)//类型
            ->where($two)//订单或标题
            ->where($shree)
            ->where($four)//时间
            ->select();
        foreach ($dataList['list'] as $k => $v) {
            //年份杂志
            if ($v['type'] == 1) {
                $dataList['list'][$k]['type_name'] = '年份杂志';
                if ($v['buy_type'] == 1) {
                    $dataList['list'][$k]['sn_content'] = '一年杂志';

                } elseif ($v['buy_type'] == 2) {
                    $dataList['list'][$k]['sn_content'] = '半年杂志';

                }
            }
            //单期杂志
            if ($v['type'] == 2) {
                $Magazine = Magazine::field('title,picture,stage')->where('id', $v['pid'])->select();
                foreach ($Magazine as $kk => $vv) {
                    $v['stage'] = $vv['stage'];
                    $v['title'] = $vv['title'];
                    $v['picture'] = $vv['picture'];
                }
                $dataList['list'][$k]['type_name'] = '单期杂志';

            }
            if ($v['type'] == 3) {
                $Course = Course::field('title,picture')->where('id', $v['pid'])->select();
                foreach ($Course as $kkk => $vvv) {
                    $v['title'] = $vvv['title'];
                    $v['picture'] = $vvv['picture'];

                }
                $dataList['list'][$k]['type_name'] = '单个小课';
            }
            if ($v['type'] == 4) {
                $TalkShow = TalkShow::field('title,picture,author')->where('id', $v['pid'])->select();
                foreach ($TalkShow as $key => $value) {
                    $v['title'] = $value['title'];
                    $v['picture'] = $value['picture'];
                    $v['author'] = $value['author'];
                }
                $dataList['list'][$k]['type_name'] = 'TalkShow';
            }
            if ($v['type'] == 5) {
                $dataList['list'][$k]['type_name'] = '会员';
//                $vip=['vip'=>'VIP会员'];
//                $dataList['list'][$k]['sn_content']=array($vip);
                $dataList['list'][$k]['sn_content'] = 'VIP会员';
            }
        }
        if (empty($dataList['list'])){
            json_fail('暂无数据');
        }

        foreach ($dataList['list'] as $i => $j) {
            $j['price'] = $j['price'] ? $j['price'] / 100 : '--';  //订单金额
            $j['nickname'] = $j['nickname'] ? base64_decode($j['nickname']) : '--';
//            $j['avatar_url'] = $j['avatar_url'] ? json_decode($j['avatar_url']) : '';
            $j['avatar_url'] = $j['avatar_url'] ? $j['avatar_url'] : '';
            $j['create_time'] = $j['create_time'] ? date('Y-m-d H:i:s', $j['create_time']) : '--';
            $j['pay_time'] = $j['pay_time'] ? date('Y-m-d H:i:s', $j['pay_time']) : '--';
            $j['picture']=$j['picture']?$j['picture']:'--';
            if (!empty($j['stage'])){
                $j['stage']=$j['stage'];
            }else{
                $j['stage']='--';
            }

            $new_info[] = array(
                'sn' => $j['sn'],
                'type' => $j['type_name'],
                'sn_content' => $j['title'],
                'picture'=>$j['picture'],
                'stage'=>$j['stage'],
                'price' => $j['price'],
                'create_time' => $j['create_time'],
                'pay_time' => $j['pay_time'],
                'avatar_url'=>$j['avatar_url'],
                'nickname'=>$j['nickname']
            );
        }

        $name = 'activity_total';
        $header = array(
            '订单编号', '订单类型', '订单内容','图片','期数', '订单金额', '下单日期', '支付日期', '用户头像', '用户昵称');
        excelExport($name, $header, $new_info);

    }

















    /**
     * 活动统计导出
     */
    public function activity_total_export()
    {
        $type = input('type', 0);
        $keys = input('keys');
        //实例化数据库
        $activity = new \app\admin\model\Activity();

        $map = array(
            'status' => array('neq', 0)
        );

        if ($keys) {
            $map['title'] = array('like', '%' . $keys . '%');
        }
        if ($type != 0) {
            $map['type'] = $type;
        }

        //查询全部活动
        $list = $activity->where($map)->order('id desc')->select();

        if (!$list) {
            json_fail('暂无数据');
        }
        if ($list) {
            foreach ($list as $k => $v) {
                $v['start_time'] = $v['start_time'] ? date('Y-m-d H:i', $v['start_time']) : '--';
                $v['end_time'] = $v['end_time'] ? date('Y-m-d H:i', $v['end_time']) : '--';
                $v['picture'] = $v['picture']?json_decode($v['picture']):[];
                if($v['type']==1){
                    $v['text']='线上';
                }
                if($v['type']==3){
                    $v['text']='线下';
                }
                $new_info[] = array(
                    'text' => $v['text'],
                    'title' => $v['title'],
                    'start_time' => $v['start_time'],
                    'end_time' => $v['end_time'],
                    'sign_count' => $v['sign_count'],
                );
            }
            $name = 'activity_total';
            $header = array(
                '活动类型', '活动名称', '活动开始时间', '活动结束时间', '报名人数');
            excelExport($name, $header, $new_info);
        } else {
            echo '暂无内容';
        }
    }

    /**
     * 活动统计明细导出
     */
    public function activity_detailed_export()
    {
        $activity_id = input('activity_id');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $keys = input('keys');

        if(!$activity_id){
            json_fail('获取活动id失败');
        }

        //实例化数据库
        $activity_order = new ActivityOrder();
        $user = new \app\admin\model\User();

        $map = array(
            'status'=>1,
            'activity_id'=>$activity_id,
        );

        if($start_time && $end_time){
            $map['create_time'] = array('between',array(strtotime($start_time),strtotime($end_time)));
        }

        $list = $activity_order->where($map)->order('id desc')->select();

        if (!$list) {
            json_fail('暂无数据');
        }

        if ($list) {
            foreach ($list as $k => $v) {
                $user_detail = $user->where(array('id'=>$v['user_id']))->field('nickname,avatar_url')->find();
                $v['avatar_url'] = $user_detail['avatar_url'];
                $v['nickname'] = $user_detail['nickname'] ? base64_decode($user_detail['nickname']):'--';
                $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i:s',$v['create_time']):'--';

                $new_info[] = array(
                    'nickname' => $v['nickname'],
                    'name' => $v['name'],
                    'mobile' => $v['mobile'],
                    'major_name' => $v['major_name'],
                    'create_time' => $v['create_time'],
                    'sn' => $v['sn'],
                );
            }
            $name = 'activity_detail';
            $header = array(
                '昵称', '真实姓名', '手机号码', '专业', '报名时间', '报名编号');
            excelExport($name, $header, $new_info);
        } else {
            echo '暂无内容';
        }
    }





    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 导出用户列表
     */
    public function user_export()
    {
        $country_id = input('country_id');
        $degree_id = input('degree_id');
        $major_id = input('major_id');
        $keys = input('keys');

        //实例化数据库
        $user = new \app\admin\model\User();
        $user_country = new UserCountry();
        $user_degree = new UserDegree();
        $user_major = new UserMajor();
        $country = new \app\admin\model\Country();
        $degree = new \app\admin\model\Degree();
        $major = new \app\admin\model\Major();
        $channel = new \app\admin\model\Channel();

        //条件
        $map = array(
            'status'=>array('neq',0)
        );
        if ($country_id) {
            $country_user_id = $user_country->where(array('country_id' => $country_id,'status'=>1))->column('user_id');
        }else{
            $country_user_id = [];
        }
        if ($degree_id) {
            $degree_user_id = $user_degree->where(array('degree_id' => $degree_id,'status'=>1))->column('user_id');
        }else{
            $degree_user_id = [];
        }
        if ($major_id) {
            $major_user_id = $user_major->where(array('major_id' => $major_id,'status'=>1))->column('user_id');
        }else{
            $major_user_id = [];
        }

        $userIds = array_merge($country_user_id, $degree_user_id, $major_user_id);
        if($userIds){
            $userIds = array_unique($userIds);
            $map['id']=array('in',$userIds);
        }
        if ($keys) {
            $map['real_name|nickname_old|mobile'] = array('like', '%' . $keys . '%');
        }

        $list = $user->where($map)->order('id desc')->select();
        if (!$list) {
            json_fail('暂无数据');
        }
        $list = collection($list)->toArray();
        if ($list) {
            foreach ($list as $k => $v) {
                $v['timestamp'] = $v['timestamp'] ? date('Y-m-d', $v['timestamp']) : '';
                //查询关注的国家
                $country_ids = $user_country->getCountryIds($v['id']);
                if ($country_ids) {
                    $v['country_name'] = $country->getName($country_ids);
                    $v['country_name'] = implode(',',$v['country_name']);
                } else {
                    $v['country_name'] = '';
                }

                //查询关注的学位
                $degree_ids = $user_degree->getDegreeIds($v['id']);
                if ($degree_ids) {
                    $v['degree_name'] = $degree->getName($degree_ids);
                    $v['degree_name'] = implode(',',$v['degree_name']);
                } else {
                    $v['degree_name'] = '';
                }

                //查询关注的专业
                $major_ids = $user_major->getMajorIds($v['id']);
                if ($major_ids) {
                    $v['major_name'] = $major->getName($major_ids);
                    $v['major_name'] = implode(',',$v['major_name']);
                } else {
                    $v['major_name'] = '';
                }

                $v['nick_name'] = $v['nickname'] ? base64_decode($v['nickname']) : '--';
                //进入方式
                if($v['source_type'] == 1){
                    $v['source_text'] = '自主进入';
                }elseif ($v['source_type']==2){
                    $v['source_text'] = '好友分享';
                }else{
                    $v['source_text'] = '渠道拉新';
                }
                //渠道
                if(($v['source_id'] != 0) && ($v['source_type'] == 3)){
                    $v['channel_name'] = $channel->where(array('id'=>$v['source_id']))->value('title');
                }else{
                    $v['channel_name'] = '';
                }
                //角色
                if($v['user_type'] == 1){
                    $v['user_type_text']='学生';
                }else{
                    $v['user_type_text']='家长';
                }
                $new_info[] = array(
                    'country_name' => $v['country_name'],
                    'degree_name' => $v['degree_name'],
                    'major_name' => $v['major_name'],
                    'nick_name' => $v['nick_name'],
                    'mobile' => $v['mobile'],
                    'source_text' => $v['source_text'],
                    'channel_name' => $v['channel_name'],
                    'user_type_text' => $v['user_type_text'],
                    'browse_count' => $v['browse_count'],
                    'drainage_count' => $v['drainage_count'],
                    'timestamp' => $v['timestamp'],
                );
            }

            $name = 'user_list';
            $header = array(
                '关注国家', '关注学位', '关注专业', '昵称', '手机号码', '进入方式', '来源渠道', '当前角色','浏览次数','引流人数','注册时间');
            excelExport($name, $header, $new_info);
        } else {
            echo '暂无内容';
        }
    }
}